﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserService.Entity;
using UserService.Repository;

namespace UserService.Business
{
    public class UserBusiness : IDisposable
    {
        private DBContext _ctx;

        private UserManager<User> _userManager;
        public UserBusiness()
        {
            _ctx = new DBContext();
            _userManager = new UserManager<User>(new UserStore(_ctx));
        }

        public User FindUser(string userName, string password)
        {
            ICollection<User> user_List =  _userManager.FindByIdToUser(userName, password);
            foreach (var b in user_List)
            {
                if (Crypto.VerifyHashedPassword(b.PasswordHash, password))
                {
                    return b;
                }
            }
            return null;
        }

        public bool InstertUser(User obj)
        {
            obj.PasswordHash = Crypto.HashPassword(obj.PasswordHash);
            return _userManager.AddUser(obj);
        }

        public void Dispose()
        {
            _ctx.Dispose();
            _userManager.Dispose();
        }
    }
}
